#!/usr/bin/env bash
# Copyright 2022 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

# This script is a wrapper creating the same user inside container as the one
# running the ci_build.sh outside the container. It also set the home directory
# for the user inside container to match the same absolute path as the workspace
# outside of container.
# We do this so that the bazel running inside container generate symbolic links
# and user permissions which makes sense outside of container.
# Do not run this manually. It does not make sense. It is intended to be called
# by ci_build.sh only.

set -e

COMMAND=("$@")

if ! touch /this_is_writable_file_system; then
  echo "You can't write to your filesystem!"
  echo "If you are in Docker you should check you do not have too many images" \
      "with too many files in them. Docker has some issue with it."
  exit 1
else
  rm /this_is_writable_file_system
fi

if [ -n "${CI_BUILD_USER_FORCE_BADNAME}" ]; then
  ADDUSER_OPTS="--force-badname"
fi

apt-get install sudo

getent group "${CI_BUILD_GID}" || addgroup ${ADDUSER_OPTS} --gid "${CI_BUILD_GID}" "${CI_BUILD_GROUP}"
getent passwd "${CI_BUILD_UID}" || adduser ${ADDUSER_OPTS} \
    --gid "${CI_BUILD_GID}" --uid "${CI_BUILD_UID}" \
    --gecos "${CI_BUILD_USER} (generated by with_the_same_user script)" \
    --disabled-password --home "${CI_BUILD_HOME}" --quiet "${CI_BUILD_USER}"
usermod -a -G sudo "${CI_BUILD_USER}"
echo "${CI_BUILD_USER} ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/90-nopasswd-sudo

if [[ "${TF_NEED_ROCM}" -eq 1 ]]; then
  # ROCm requires the video group in order to use the GPU for compute. If it
  # exists on the host, add it to the container.
  getent group video || addgroup video && adduser "${CI_BUILD_USER}" video
fi

if [ -e /root/.bazelrc ]; then
  cp /root/.bazelrc "${CI_BUILD_HOME}/.bazelrc"
  chown "${CI_BUILD_UID}:${CI_BUILD_GID}" "${CI_BUILD_HOME}/.bazelrc"
fi

sudo -u "#${CI_BUILD_UID}" --preserve-env "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}" \
"HOME=${CI_BUILD_HOME}" ${COMMAND[@]}
